//
//  HOReportListViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/9/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOReportListViewController.h"
#import "HOReportListTableViewCell.h"
#import "HOReportEntity.h"
#import "HOUtils.h"
#import "HOConstants.h"
#import "HOReportOrderEntity.h"
#import "HODefine.h"
#import "HOViewStatusViewController.h"
#import "HOConfirmOrderViewController.h"
#import "HOReportDetailViewController.h"
#import "HOButton.h"
#import "HOStaticDataMgr.h"
#import "HOBaseRequestEntity.h"
#import "HORepaireDoneViewController.h"
#import "HOReportLocationViewController.h"
#import "HOAreaEntity.h"
#import "UIImageView+WebCache.h"
#import "NSString+Extension.h"

@interface HOReportListViewController ()<HOReportLocationViewControllerDelegate>
{
	NSMutableDictionary *dataDic;
	NSMutableDictionary *entityDic;
	BOOL 				needShowTabBar;
	UIView 				*statusSelectView;
	UILabel 			*statusLbl;
	
	UIButton 			*gotoTopBtn;
}
@property(nonatomic, retain)HOBaseRequestEntity *orderRequest;
@property(nonatomic, retain)NSObject *lockObj;
@property(nonatomic, retain)UIView 		*menuPanelView;
@property(nonatomic, retain)HOAreaEntity	*firstAreaEntity;
@property(nonatomic, retain)HOAreaEntity	*secondEntityEntity;
@property(nonatomic, retain)HOAreaEntity	*thirdAreaEntity;
@end

@implementation HOReportListViewController
@synthesize displayBackBtn;
@synthesize currentStatus = _currentStatus;
- (void)viewDidLoad
{
	[super viewDidLoad];
	[self initSubviews];
	[self initDataSource];
//	[self requestDataWithMaxId:1 withStatus:self.currentStatus];

}

- (void)initSubviews
{
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	[self initTableView];
	[self registerTapGesture];
	//	[self initTestData];
	[self initStatusSelectView];
	[self initPickerView];
	[self initNoDataView];
	self.menuPanelView = [self createMenuItem];
//	baseTableview.layer.borderWidth = 1;
	
	gotoTopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	gotoTopBtn.frame = CGRectMake(self.view.frame.size.width - 40, self.view.frame.size.height - 140 - [HOUtils getStatusBarHeight] - 30, 40, 40);
	[gotoTopBtn setImage:[UIImage imageNamed:@"ic_go_to_top"] forState:UIControlStateNormal];
	[self.view addSubview:gotoTopBtn];
	[gotoTopBtn addTarget:self action:@selector(gotoTop:) forControlEvents:UIControlEventTouchUpInside];
	gotoTopBtn.alpha = 0.8;
	gotoTopBtn.hidden = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	gotoTopBtn.hidden = scrollView.contentOffset.y <= 100;
}

- (void)gotoTop:(id)sender
{
	[baseTableview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}

- (void)initDataSource
{
//	self.currentStatus = HO_REPORT_ORDER_UNACCEPT;
	//	[self requestDataWithMaxId:1 withStatus:self.currentStatus];
	dataDic = [[NSMutableDictionary alloc] init];
	entityDic = [[NSMutableDictionary alloc] init];
	self.lockObj = [[[NSObject alloc] init] autorelease];
}

- (UIView *)createMenuItem
{
	UIView *view = [[[UIView alloc]
					 initWithFrame:CGRectMake(self.view.frame.size.width - 151,
											  0,
											  150,
											  2 * 35)] autorelease];
	
	[view addSubview:[self createMenuItemWithTitle:@"显示全部"
									  withSelector:@selector(displayAll:)
											 withY:0 * 35
										   withTag:0]];
	
	[view addSubview:[self createMenuItemWithTitle:@"按报修地点过滤"
									  withSelector:@selector(filterArea:)
											 withY:1 * 35
										   withTag:1]];
	[view setBackgroundColor:[UIColor whiteColor]];
	view.layer.shadowOffset = CGSizeMake(0.0, 0.0); //shadow on the right and bottom sides.
	view.layer.shadowRadius = 4.0;
	view.layer.shadowOpacity = 0.25;
	[self.view addSubview:view];
	view.hidden = YES;
	return view;
}

- (void)displayAnalysis:(UIButton *)btn
{
	HO_REPORT_ORDER_STATUS status = (HO_REPORT_ORDER_STATUS)btn.tag;
	self.currentStatus = status;
	NSArray *array = [self getDataListWithStatus:status];
	HOReportOrderEntity *entity = [array lastObject];
	if(entity != nil)
	{
		[self requestDataWithMaxId:entity.orderId withStatus:status];
	}
	else
	{
		[self requestDataWithMaxId:1 withStatus:status];
	}
}

- (UIButton *)createMenuItemWithTitle:(NSString *)title withSelector:(SEL)selector withY:(CGFloat)y withTag:(NSInteger)tag
{
	UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
	btn.frame = CGRectMake(- 1,
						   y,
						   152,
						   35);
	
	[btn setTitle:title forState:UIControlStateNormal];
	btn.layer.borderColor = UIColorFromRGB(0xcdcdcd).CGColor;
	btn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	[btn setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
	btn.titleLabel.font = [UIFont systemFontOfSize:14];
	[btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
	btn.tag = tag;
	return btn;
}

- (void)dealloc
{
	[entityDic removeAllObjects];
	[dataDic removeAllObjects];
	[entityDic release];
	entityDic = nil;
	[dataDic release];
	self.orderRequest = nil;
	self.lockObj = nil;
	[statusLbl release];
	[statusSelectView release];
	[super dealloc];
}

- (NSMutableArray *)getDataListWithStatus:(HO_REPORT_ORDER_STATUS)status
{
	NSString *key = [NSString stringWithFormat:@"%d", status];
	NSMutableArray *array = [dataDic objectForKey:key];
	if(array == nil)
	{
		array = [[NSMutableArray alloc] init];
		[dataDic setObject:array forKey:key];
		[array release];
	}
	array = [dataDic objectForKey:key];
	return array;
}

- (void)clearData
{
	for(NSNumber *key in dataDic)
	{
		NSMutableArray *array = [dataDic objectForKey:key];
		[array removeAllObjects];
	}
	[baseTableview reloadData];
}

//- (void)initTestData
//{
//	for(int i = 0; i < 10; i ++)
//	{
//		HOReportEntity *entity = [[HOReportEntity alloc] init];
//		[self.tableViewDataList addObject:entity];
//		entity.title = @"3180";
//		entity.url = @"http://pic.4j4j.cn/upload/pic/20130607/8ed20e2a77.jpg";
//		entity.department =@"东十六病房";
//		entity.content = @"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
//		entity.time = [HOUtils getCurrentTime];
//	}
//}

- (void)pullUpToRefresh
{
	HO_REPORT_ORDER_STATUS status = (HO_REPORT_ORDER_STATUS)pickerViewSelectRow;
	[pickerViewImp selectRow:pickerViewSelectRow inComponent:0 animated:YES];
	[self doRequestWithStatus:status];
}

- (void)pullDownToRefresh
{
	HO_REPORT_ORDER_STATUS status = (HO_REPORT_ORDER_STATUS)pickerViewSelectRow;
	NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
	[array removeAllObjects];
	[self requestDataWithMaxId:1 withStatus:status];
	
}


- (void)requestDataWithMaxId:(int)maxId withStatus:(int)status
{
	if(maxId == 1)
	{
		@synchronized(self.lockObj) {
			NSMutableArray *array = [self getDataListWithStatus:status];
			[array removeAllObjects];
			[baseTableview reloadData];
		}
	}
	self.menuPanelView.hidden = YES;
	NSMutableDictionary *dic = nil;
	if(self.isForSingleStatus)
	{
		dic = [[NSMutableDictionary alloc] initWithDictionary:@{kHO_FIELD_Action:kHO_ACTION_GetOrderList,
																kHO_FIELD_MaxID:[NSNumber numberWithInt:maxId],
																kHO_FIELD_Status:[NSNumber numberWithInt:status],
																kHO_FIELD_DataType:[NSNumber numberWithInt:2]}];
	}
	else
	{
		dic = [[NSMutableDictionary alloc] initWithDictionary:@{kHO_FIELD_Action:kHO_ACTION_GetOrderList,
																kHO_FIELD_MaxID:[NSNumber numberWithInt:maxId],
																kHO_FIELD_Status:[NSNumber numberWithInt:status],
																kHO_FIELD_DataType:[NSNumber numberWithInt:0]}];
	}
	if(self.firstAreaEntity)
	{
		[dic setObject:[NSNumber numberWithInt:self.firstAreaEntity.areaId] forKey:kHO_FIELD_FaultArea];
	}
	[self sendRequestWithParams:dic];
}

- (void)viewWillAppear:(BOOL)animated
{
	self.navigationItem.hidesBackButton = !self.displayBackBtn;
	self.tabBarController.tabBar.hidden = self.displayBackBtn;
	[super viewWillAppear:animated];
	pickerViewSelectRow = self.currentStatus;
	if(self.navTitle == nil)
	{
		[self setNavigationItemTitle:NSLocalizedString(@"报修列表", @"报修列表")];
	}
	else
	{
		[self setNavigationItemTitle:self.navTitle];
	}
	needShowTabBar = !self.displayBackBtn;
	[baseTableview clearsContextBeforeDrawing];
	self.tabBarController.tabBar.hidden = self.displayBackBtn;
	baseTableview.frame = CGRectMake(0,
									 statusSelectView.frame.size.height,
									 self.view.frame.size.width,
									 [HOUtils getScreenHeight] - [HOUtils getStatusBarHeight] - 49 - (self.isForSingleStatus ? 0 : (statusSelectView.frame.size.height + 44)) );
	if(!self.isRequestTheFirst)
	{
		self.isRequestTheFirst = YES;
		[self requestDataWithMaxId:1 withStatus:self.currentStatus];
	}
	[self displayRightButtomItemWithTitle:@"过滤"];
}

- (void)rightButtonItemDidClick
{
	[self showPickerView:NO];
	self.menuPanelView.hidden = !self.menuPanelView.hidden;
}

- (void)displayAll:(id)sender
{
	NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
	[array removeAllObjects];
	self.firstAreaEntity = nil;
	self.secondEntityEntity = nil;
	self.thirdAreaEntity = nil;
	[self requestDataWithMaxId:1 withStatus:self.currentStatus];
}

- (void)filterArea:(id)sender
{
	HOReportLocationViewController *viewCtrl = [[HOReportLocationViewController alloc] init];
	viewCtrl.delegate = self;
	viewCtrl.isSelectedTheFirstArea = YES;
//	[viewCtrl initSearchBar];
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];

}

#pragma mark
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	self.menuPanelView.hidden = YES;
	[self hideKeyboard];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	NSArray *array = [HOUtils getReportOrderStatus];
	return [array count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	HO_REPORT_ORDER_STATUS status = [[[HOUtils getReportOrderStatus] objectAtIndex:row] intValue];
	return [HOUtils getDescribtionWithStatus:status];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	self.menuPanelView.hidden = YES;
	pickerViewSelectRow = row;
}

- (void)didPickDone:(id)sender
{
	[super didPickDone:nil];
	HO_REPORT_ORDER_STATUS status = [[[HOUtils getReportOrderStatus] objectAtIndex:pickerViewSelectRow] intValue];
	[self doRequestWithStatus:status];
}

- (void)doRequestWithStatus:(HO_REPORT_ORDER_STATUS)status
{
	self.currentStatus = status;
	NSString *title = [HOUtils getDescribtionWithStatus:self.currentStatus];
	
	statusLbl.text = title;
	NSArray *array = [self getDataListWithStatus:status];
	HOReportOrderEntity *entity = [array lastObject];
	if(entity != nil)
	{
		[self requestDataWithMaxId:entity.orderId withStatus:status];
	}
	else
	{
		[self requestDataWithMaxId:1 withStatus:status];
	}
}

- (void)showPickerView:(BOOL)show
{
	[pickerViewImp selectRow:self.currentStatus inComponent:0 animated:YES];
	[super showPickerView:show];
	if(needShowTabBar && !self.isForSingleStatus)
	{
		self.tabBarController.tabBar.hidden = NO;
	}
	else
	{
		self.tabBarController.tabBar.hidden = YES;
	}
}
- (void)didChangeStatus:(id)sender
{
	self.menuPanelView.hidden = YES;
	[self showPickerView:YES];
}

#pragma mark -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.row == 0)
	{
		NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
		HOReportOrderEntity *entity = [array objectAtIndex:indexPath.section];
		CGFloat width = tableView.frame.size.width - 78.0f;
		NSString *address = [NSString stringWithFormat:@"故障位置:%@", [HOUtils getValideString:entity.address]];
		CGSize addressSize = [address sizeWithFont:[UIFont systemFontOfSize:12] maxW:width];
		NSString *content = [NSString stringWithFormat:@"故障描述:%@", [entity getFaultDetailContent]];
		CGSize contentSize = [content sizeWithFont:[UIFont systemFontOfSize:14] maxW:width];
		CGFloat height = 26 + 26 + 4 + 8 + MAX(addressSize.height, 20) +  MAX(contentSize.height, 20) + 8;
		return height;
	}
	else if(indexPath.row == 1)
		return 44;
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	@synchronized(self.lockObj)
	{
		NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
		NSInteger count = [array count];
		[self showNoDataView:count == 0];
   	 	return count;
	}
}

- (NSInteger)getListCount
{
	@synchronized(self.lockObj)
	{
		NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
		NSInteger count = [array count];
		return count;
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 2;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if(section == 0)
		return [HOUtils defaultOnePixelConversion];
	return SECTION_PADDING / 2;
}

- (void)initStatusSelectView
{
	if(self.isForSingleStatus)
		return;
	statusSelectView = [[UIView alloc]
					initWithFrame:CGRectMake(0,
											 0,
											 self.view.frame.size.width,
											 44)];
//	statusSelectView.layer.borderWidth = 1;
	[statusSelectView setBackgroundColor:[UIColor whiteColor]];
	NSString *title = [HOUtils getDescribtionWithStatus:self.currentStatus];
	
	UIButton *btn = [[UIButton alloc]
						initWithFrame:CGRectMake(0,
												 0,
												 self.view.frame.size.width,
												 44)];
	btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
	
	//		[btn setTitle:title forState:UIControlStateNormal];
	[btn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xf0f0f0) forView:btn] forState:UIControlStateNormal];
	[btn setTitleColor:TEXT_COLOR_181818 forState:UIControlStateNormal];
	[btn addTarget:self action:@selector(didChangeStatus:) forControlEvents:UIControlEventTouchUpInside];
	[statusSelectView addSubview:btn];
	[btn release];
	
	statusLbl = [[UILabel alloc]
					initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											 (44 - 22) / 2,
											 200,
											 22)];
	statusLbl.text = title;
	statusLbl.font = [UIFont systemFontOfSize:15];
	statusLbl.textColor = TEXT_COLOR_666666;
	[statusSelectView addSubview:statusLbl];
	
	UIImageView *imgView = [[UIImageView alloc]
							initWithFrame:CGRectMake(self.view.frame.size.width - 16 - HO_HORIZONAL_PADDING,
													 (44 - 9) / 2,
													 16,
													 9)];
	imgView.image = [UIImage imageNamed:@"ic_baoxiuliebiao_zhankai"];
	[statusSelectView addSubview:imgView];
	[imgView release];
	[self.view addSubview:statusSelectView];
	baseTableview.frame = CGRectMake(0,
									 statusSelectView.frame.size.height,
									 self.view.frame.size.width,
									 self.view.frame.size.height - statusSelectView.frame.size.height);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
	HOReportOrderEntity *entity = [array objectAtIndex:indexPath.section];
	
	if(indexPath.row == 0)
	{
//		static NSString *ReportTableViewCellIdentifier = @"ReportTableViewCellIdentifier";
//		HOReportListTableViewCell *cell = (HOReportListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ReportTableViewCellIdentifier];
//		if(cell == nil)
//		{
//			NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"HOReportListTableViewCell" owner:self options:nil];
//			cell = [nib firstObject];
//			cell.selectionStyle = UITableViewCellSelectionStyleGray;
//		}
//		cell.selectionStyle = UITableViewCellSelectionStyleNone;
//		[cell setReportEntity:entity];
//		return cell;

		static NSString *ReportTableViewCellIdentifier = @"ReportTableViewCellIdentifier2";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:ReportTableViewCellIdentifier];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]init] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleGray;
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		UIImageView *imgView = (UIImageView *)[cell viewWithTag:111];
		if(imgView == nil)
		{
			imgView = [[UIImageView alloc] initWithFrame:CGRectMake(HO_HORIZONAL_PADDING, HO_HORIZONAL_PADDING, 48, 48)];
			//			imgView.layer.borderWidth = 1;
			[cell.contentView addSubview:imgView];
			imgView.tag = 111;
		}
		NSURL *imgURL = [NSURL URLWithString:[HOUtils getValideString:entity.image]];
		[imgView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"morentu"]];
		
		UIImageView *urgentImgView = (UIImageView *)[cell viewWithTag:141];
		if(urgentImgView == nil)
		{
			urgentImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 48, 48)];
			//			imgView.layer.borderWidth = 1;
			[cell.contentView addSubview:urgentImgView];
			urgentImgView.tag = 141;
			urgentImgView.image = [UIImage imageNamed:@"icon_urgent"];
		}
		urgentImgView.hidden = !entity.isUrgent;
		
		
		UILabel *statusLbl = (UILabel *)[cell viewWithTag:113];
		if(statusLbl == nil)
		{
			statusLbl = [[UILabel alloc] initWithFrame:CGRectMake(HO_HORIZONAL_PADDING * 2 + imgView.frame.size.width,
																  HO_HORIZONAL_PADDING,
																  tableView.frame.size.width - 58 - 120,
																  22)];
			//			statusLbl.layer.borderWidth = 1;
			statusLbl.textColor = TEXT_COLOR_666666;
			statusLbl.font = [UIFont systemFontOfSize:15];
			[cell.contentView addSubview:statusLbl];
			statusLbl.tag = 113;
		}
		statusLbl.attributedText = [HOUtils getAttributedStringWithTitle:@"状态:" withContent:[entity getStatusStr] withColor:[HOUtils getOrderColorWithStatus:entity.status]];
		
		
		UILabel *orderIdLbl = (UILabel *)[cell viewWithTag:112];
		if(orderIdLbl == nil)
		{
			orderIdLbl = [[UILabel alloc] initWithFrame:CGRectMake(statusLbl.frame.origin.x,
																   statusLbl.frame.origin.y + statusLbl.frame.size.height + 4,
																   tableView.frame.size.width - imgView.frame.size.width - 3 * HO_HORIZONAL_PADDING,
																   22)];
			//			orderIdLbl.layer.borderWidth = 1;
			orderIdLbl.textColor = TEXT_COLOR_666666;
			orderIdLbl.font = [UIFont systemFontOfSize:12];
			[cell.contentView addSubview:orderIdLbl];
			orderIdLbl.tag = 112;
		}
		
		
		orderIdLbl.attributedText = [HOUtils getAttributedStringWithTitle:@"单号:" withContent:[NSString stringWithFormat:@"%d", entity.orderSN] withColor:nil];
		
		
		UILabel *timeLbl = (UILabel *)[cell viewWithTag:114];
		if(timeLbl == nil)
		{
			timeLbl = [[UILabel alloc] initWithFrame:CGRectMake(tableView.frame.size.width - 120,
																HO_HORIZONAL_PADDING,
																110,
																22)];
			//			timeLbl.layer.borderWidth = 1;
			timeLbl.textColor = TEXT_COLOR_666666;
			timeLbl.textAlignment = NSTextAlignmentRight;
			timeLbl.font = [UIFont systemFontOfSize:12];
			[cell.contentView addSubview:timeLbl];
			timeLbl.tag = 114;
		}
		timeLbl.text = [HOUtils getDateFromTimeInterval:entity.createTime * 1000];
		
		
		
		UILabel *locationLbl = (UILabel *)[cell viewWithTag:115];
		if(locationLbl == nil)
		{
			locationLbl = [[UILabel alloc] initWithFrame:CGRectMake(orderIdLbl.frame.origin.x,
																	orderIdLbl.frame.origin.y + orderIdLbl.frame.size.height + 6,
																	tableView.frame.size.width - imgView.frame.size.width - 3 * HO_HORIZONAL_PADDING,
																	22)];
			//			locationLbl.layer.borderWidth = 1;
			locationLbl.textColor = TEXT_COLOR_666666;
			locationLbl.font = [UIFont systemFontOfSize:12];
			[cell.contentView addSubview:locationLbl];
			locationLbl.numberOfLines = 2;
			
			locationLbl.tag = 115;
		}
		locationLbl.attributedText = [HOUtils getAttributedStringWithTitle:@"故障位置:" withContent:entity.address withColor:nil];
		
		[locationLbl sizeToFit];
		
		UILabel *contentLbl = (UILabel *)[cell viewWithTag:116];
		if(contentLbl == nil)
		{
			contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(locationLbl.frame.origin.x,
																   locationLbl.frame.origin.y + locationLbl.frame.size.height + 4,
																   tableView.frame.size.width - imgView.frame.size.width - 3 * HO_HORIZONAL_PADDING,
																   22)];
			//			contentLbl.layer.borderWidth = 1;
			contentLbl.textColor = TEXT_COLOR_666666;
			contentLbl.font = [UIFont systemFontOfSize:14];
			contentLbl.numberOfLines = 2;
			[cell.contentView addSubview:contentLbl];
			contentLbl.textColor = [UIColor blackColor];
			contentLbl.tag = 116;
		}
		if([entity getFaultDetailContent].length > 0)
		{
			contentLbl.attributedText = [HOUtils getAttributedStringWithTitle:@"故障描述:" withContent:[entity getFaultDetailContent]  withColor:nil];
		}
		else
		{
			contentLbl.attributedText = [HOUtils getAttributedStringWithTitle:@"" withContent:[entity getFaultDetailContent]  withColor:nil];
		}
		[contentLbl sizeToFit];
		return cell;
	}
	else if(indexPath.row == 1)
	{
		static NSString *HOReportListTableViewCell = @"HOReportListTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOReportListTableViewCell];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOReportListTableViewCell] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
//		HOButton *takeReportBtn = (HOButton *)[cell viewWithTag:126];
//		if(takeReportBtn == nil)
//		{
//			takeReportBtn = [[[HOButton alloc]
//						   initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
//													7,
//													80,
//													30)] autorelease];
//
//			takeReportBtn.tag = 126;
//			[takeReportBtn setTitle:NSLocalizedString(@"接单", @"接单") forState:UIControlStateNormal];
//			takeReportBtn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
//			takeReportBtn.layer.borderColor = TEXT_COLOR_009BD3.CGColor;
//			[takeReportBtn setTitleColor:MAIN_COLOR_NORMAL forState:UIControlStateNormal];
//			[takeReportBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xcccccc) forView:takeReportBtn] forState:UIControlStateSelected];
//			[takeReportBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xcccccc) forView:takeReportBtn] forState:UIControlStateHighlighted];
//			takeReportBtn.layer.cornerRadius = 5;
//			[takeReportBtn addTarget:self action:@selector(takeReport:) forControlEvents:UIControlEventTouchUpInside];
//			takeReportBtn.titleLabel.font = [UIFont systemFontOfSize:13];
//			[cell.contentView addSubview:takeReportBtn];
//		}
//		takeReportBtn = (HOButton *)[cell viewWithTag:126];
//		takeReportBtn.data = entity;
//
//		if( [[[HOStaticDataMgr sharedInstance] getUserInfo] isRepairUser]
//		   &&  [[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId] != entity.doneId
//		   && (entity.status == HO_REPORT_ORDER_UNACCEPT))
//		{
//			takeReportBtn.hidden = NO;
//		}
//		else
//		{
//			takeReportBtn.hidden = YES;
//		}

		
		HOButton *confirmBtn = (HOButton *)[cell viewWithTag:116];
		if(confirmBtn == nil)
		{
			confirmBtn = [[[HOButton alloc]
							  initWithFrame:CGRectMake([HOUtils getScreenWidth] - 80 * 2 - HO_HORIZONAL_PADDING * 2,
													   7,
													   80,
													   30)] autorelease];
			
			confirmBtn.tag = 116;
			[confirmBtn setTitle:NSLocalizedString(@"确认完成", @"确认完成") forState:UIControlStateNormal];
			confirmBtn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			confirmBtn.layer.borderColor = TEXT_COLOR_009BD3.CGColor;
			[confirmBtn setTitleColor:MAIN_COLOR_NORMAL forState:UIControlStateNormal];
			[confirmBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xcccccc) forView:confirmBtn] forState:UIControlStateSelected];
			[confirmBtn setBackgroundImage:[HOUtils createImageWithColor:UIColorFromRGB(0xcccccc) forView:confirmBtn] forState:UIControlStateHighlighted];
			confirmBtn.layer.cornerRadius = 5;
			[confirmBtn addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
			confirmBtn.titleLabel.font = [UIFont systemFontOfSize:13];
			[cell.contentView addSubview:confirmBtn];
		}
		confirmBtn = (HOButton *)[cell viewWithTag:116];
		confirmBtn.data = entity;
		int myUserId =  [[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId];
		if(entity.status == HO_REPORT_ORDER_ACCEPTED
		   && [[[HOStaticDataMgr sharedInstance] getUserInfo] isRepairUser]
		    && entity.doneId == myUserId)
		{
			[confirmBtn setTitle:NSLocalizedString(@"维修完成", @"维修完成") forState:UIControlStateNormal];
			confirmBtn.hidden = NO;
		}
		else if(entity.status == HO_REPORT_ORDER_REPAIRED && entity.postId == myUserId)
		{
			[confirmBtn setTitle:NSLocalizedString(@"确认完成", @"确认完成") forState:UIControlStateNormal];
			confirmBtn.hidden = NO;
		}
		else
		{
			confirmBtn.hidden = YES;
		}
		
		HOButton *viewStatusBtn = (HOButton *)[cell viewWithTag:115];
		if(viewStatusBtn == nil)
		{
			
			viewStatusBtn = [[[HOButton alloc]
						   initWithFrame:CGRectMake([HOUtils getScreenWidth] - 80 - HO_HORIZONAL_PADDING,
													   7,
													   80,
													   30)] autorelease];
			
			
			[viewStatusBtn setTitle:NSLocalizedString(@"查看进度", @"查看进度") forState:UIControlStateNormal];
			
			viewStatusBtn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			viewStatusBtn.layer.borderColor = TEXT_COLOR_666666.CGColor;
			viewStatusBtn.titleLabel.font = [UIFont systemFontOfSize:13];
			viewStatusBtn.layer.cornerRadius = 5;
			viewStatusBtn.tag = 115;
			[viewStatusBtn setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
			[viewStatusBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
			[viewStatusBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
			[viewStatusBtn addTarget:self action:@selector(viewStatus:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:viewStatusBtn];
		}
		viewStatusBtn = (HOButton *)[cell viewWithTag:115];
		viewStatusBtn.data = entity;
		return cell;
	}
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	@synchronized(self.lockObj)
	{
		HOReportDetailViewController *viewCtrl = [[HOReportDetailViewController alloc] init];
		viewCtrl.reportType = HO_REPORT_TYPE_NORMAL;
		NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
		HOReportOrderEntity *entity = [array objectAtIndex:indexPath.section];
		viewCtrl.orderEntity = entity;
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
}



- (void)viewStatus:(HOButton *)sender
{
	HOViewStatusViewController *viewCtrl = [[HOViewStatusViewController alloc] init];
	viewCtrl.orderEntity = sender.data;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

//- (void)takeReport:(HOButton *)sender
//{
//	HOReportOrderEntity *orderEntity = (HOReportOrderEntity *)sender.data;
//	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_ReAssignFault,
//								  kHO_FIELD_OrderId:[NSNumber numberWithInt:orderEntity.orderId],
//								  kHO_FIELD_AssignId:[NSNumber numberWithInt:[[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId]],
//								  kHO_FIELD_RecordStatus:[NSNumber numberWithInteger:1],
//								  kHO_FIELD_Content:@""}];
//}

- (void)confirm:(HOButton *)sender
{
	HOReportOrderEntity *orderEntity = (HOReportOrderEntity *)sender.data;
	int myUserId =  [[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId];
	if(orderEntity.status == HO_REPORT_ORDER_ACCEPTED && [[[HOStaticDataMgr sharedInstance] getUserInfo] isRepairUser])
	{
		HORepaireDoneViewController *viewCtrl = [[HORepaireDoneViewController alloc] init];
		viewCtrl.orderId = orderEntity.orderId;
		viewCtrl.isAssistantReport = (orderEntity.owerId != 0);
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
	else if(orderEntity.status == HO_REPORT_ORDER_REPAIRED && orderEntity.postId == myUserId)
	{
		if(orderEntity.doneId == 0)
		{
			[self popupHintView:NSLocalizedString(@"此报修单还未维修完成，暂不能确认完成", @"此报修单还未维修完成，暂不能确认完成")];
			return;
		}
		
		HOConfirmOrderViewController *viewCtrl = [[HOConfirmOrderViewController alloc] init];
		viewCtrl.orderEntity = orderEntity;
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
}

#pragma mark

#pragma mark -- tool
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)didReceiveCommand:(NSString *)action data:(id)data
{
	if([action isEqualToString:kHO_CMD_Logout] || [action isEqualToString:kHO_CMD_SWITCH_COMPANY])
	{
		[self cleanup];
	}
	else if([action isEqualToString:kHO_CMD_Report_List_Changed])
	{
//		[self pullDownToRefresh];
		
		[self requestDataWithMaxId:1 withStatus:self.currentStatus];
	}
	else if([action isEqualToString:kHO_CMD_ReceiveNotificationMessage])
	{
		NSDictionary *dic = [data objectForKey:kHO_FIELD_Extras];
		int type = [[dic valueForKey:kHO_FIELD_SendType] intValue];
		if(type == HO_NC_TYPE_REPORT)
		{
			[self requestDataWithMaxId:1 withStatus:self.currentStatus];
		}
	}
	else if([action isEqualToString:kHO_CMD_Report_Detail_Changed])
	{
		self.isRequestTheFirst = NO;
//		[self requestDataWithMaxId:1 withStatus:self.currentStatus];
	}
	
	
}

- (void)cleanup
{
	
//	self.currentStatus = HO_REPORT_ORDER_UNACCEPT;
	[self.orderRequest cancelRequest];
	
	[baseTableview clearsContextBeforeDrawing];
	
	@synchronized(self.lockObj)
	{
		[self clearData];
		[dataDic removeAllObjects];
		[entityDic removeAllObjects];
		
	}
}

- (void)didReceiveResponse:(HOBaseResponseEntity *)response
{
	[super didReceiveResponse:response];
	if([response isEqualAction:kHO_ACTION_GetOrderList])
	{
		HO_REPORT_ORDER_STATUS requestOrderStatus = [[response.baseRequest.params objectForKey:kHO_FIELD_Status] intValue];
		if(self.currentStatus != requestOrderStatus)
		{
			return;
		}
		self.orderRequest = response.baseRequest;
	}
}

- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_GetOrderList])
	{
		HO_REPORT_ORDER_STATUS requestOrderStatus = [[response.baseRequest.params objectForKey:kHO_FIELD_Status] intValue];
		if(self.currentStatus != requestOrderStatus)
		{
			return;
		}
		[self performSelectorOnMainThread:@selector(didGetList:) withObject:response.dataNode waitUntilDone:YES];

	}
	else if([response isEqualAction:kHO_ACTION_ReAssignFault])
	{
		[self requestDataWithMaxId:1 withStatus:self.currentStatus];
	}
	
	
}

- (void)setCurrentStatus:(HO_REPORT_ORDER_STATUS)currentStatus
{
	_currentStatus = currentStatus;
}

- (void)didGetList:(NSArray *)list
{
	NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
	for(int i = 0; i < [list count]; i ++)
	{
		NSDictionary *dic = [list objectAtIndex:i];
		HOReportOrderEntity *entity = [self getReportOrderEntityWithId:[[dic objectForKey:kHO_FIELD_OrderId] intValue]];
		
		if(![array containsObject:entity])
		{
			[array addObject:entity];
		}
		[entity parseDic:dic];
	}
	[self doneLoadingTableViewRefresh];
}

- (HOReportOrderEntity *)getReportOrderEntityWithId:(int)orderId
{
	HOReportOrderEntity *entity = [entityDic objectForKey:[NSNumber numberWithInt:orderId]];
	if(entity == nil || ![entity isKindOfClass:[HOReportOrderEntity class]])
	{
		entity = [[[HOReportOrderEntity alloc] init] autorelease];
		entity.orderId = orderId;
		[entityDic setObject:entity forKey:[NSNumber numberWithInt:orderId]];
	}
	return entity;
}

- (void)didSelectAreaEntity:(HOAreaEntity *)entity secondEntity:(HOAreaEntity *)secondEntity withThirdArea:(HOAreaEntity *)thirdEntity
{
	NSMutableArray *array = [self getDataListWithStatus:self.currentStatus];
	[array removeAllObjects];
	self.firstAreaEntity = entity;
	self.secondEntityEntity = secondEntity;
	self.thirdAreaEntity = thirdEntity;
	[self requestDataWithMaxId:1 withStatus:self.currentStatus];
}


@end
